<template>
  <div class="header">
    <!-- 头部 -->
    <el-card class="search" shadow="never">
      <el-form :inline="true" :model="formData" class="form-inline">
        <el-form-item label="工单编号:">
          <el-input
            v-model="formData.taskCode"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="工单状态:">
          <el-select v-model="formData.status" placeholder="请选择" clearable>
            <el-option
              :label="item.statusName"
              :value="item.statusId"
              v-for="item in allTaskStatus"
              :key="item.statusId"
            ></el-option>
            <i slot="suffix" class="el-input__icon el-icon-date"></i>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 头部 -->
    <!-- 表格区域 -->
    <el-card shadow="never" class="result">
      <!-- 新建 工单配置 -->
      <el-row class="operation">
        <el-button
          type="warning"
          class="el-button--second"
          icon="el-icon-circle-plus-outline"
          @click="addFn"
          >新建</el-button
        >
        <el-button class="el-button--first" @click="configFn"
          >工单配置</el-button
        >
      </el-row>
      <!-- 表格区域 -->
      <el-table
        :stripe="false"
        :data="tableData"
        highlight-current-row
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80">
        </el-table-column>
        <el-table-column property="taskCode" label="工单编号" width="150">
        </el-table-column>
        <el-table-column property="innerCode" label=" 设备编号" width="135">
        </el-table-column>
        <el-table-column
          property="taskType.typeName"
          label="工单类型"
          width="135"
        >
        </el-table-column>
        <el-table-column
          property="createType"
          :formatter="formatterCreateType"
          label="工单方式"
          width="100"
        >
        </el-table-column>
        <el-table-column
          property="taskStatusTypeEntity.statusName"
          label="工单状态"
          width="100"
        >
        </el-table-column>
        <el-table-column property="userName" label="运营人员" width="135">
        </el-table-column>
        <el-table-column
          property="createTime"
          :formatter="formatterCreateTime"
          label="创建日期"
          width="180"
        >
        </el-table-column>
        <el-table-column label="操作" width="135">
          <template v-slot="{ row }">
            <el-button type="text" size="small" @click="clickDetailFn(row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-if="page.totalCount > 10"
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
        :current-page.sync="page.pageIndex"
        :page-size="page.pageSize"
        layout="slot,prev, next"
      >
        <template>
          <span class="el-pagination__total"
            >共{{ page.totalCount }}条记录&nbsp;&nbsp;第&nbsp;{{
              page.pageIndex
            }}/{{ page.totalPage }}页</span
          >
        </template>
      </el-pagination>
      <!-- 分页 -->
    </el-card>
    <!-- 表格区域 -->

    <!-- 新建 工单弹窗 -->
    <el-dialog
      title="新增工单"
      :visible.sync="addVisible"
      width="630px"
      :before-close="addClose"
      class="addDialog"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="140px"
        class="addForm"
      >
        <el-form-item label="设备编号:" prop="innerCode">
          <el-input
            style="width: 80%"
            v-model="addForm.innerCode"
            placeholder="请输入"
            maxlength="15"
            show-word-limit
            @change="getOperatorList"
          ></el-input>
        </el-form-item>
        <el-form-item label="工单类型:" prop="productType">
          <el-select
            v-model="addForm.productType"
            style="width: 80%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in buhuoTaskType"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补货数量:" prop="">
          <el-button icon="el-icon-edit" type="text" @click="buhuoDetailFn"
            >补货清单</el-button
          >
          <!-- 补货清单弹窗 -->
          <el-dialog
            title="补货详情"
            :visible.sync="buhuoVisible"
            width="630px"
            :before-close="buhuoClose"
            class="replenishDialog"
            append-to-body
          >
          <!-- 点击 补货清单 有个弹窗！！ -->
         <BuHuo   :channelList="channelList"
                    :isShow="isShow"> </BuHuo>
         <span slot="footer" class="dialog-footer">
              <el-button
                @click="buhuoClose"
                type="primary"
                class="el-button--first"
                >取 消</el-button
              >
              <el-button
                type="danger"
                class="el-button--second"
                @click="buhuoSubmit"
                >确 定</el-button
              >
            </span>
          </el-dialog>
          <!-- 补货清单弹窗 -->
        </el-form-item>
        <el-form-item label="运营人员:" prop="username">
          <el-select
            v-model="addForm.username"
            style="width: 80%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in operatorList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="desc">
          <el-input
            style="width: 80%"
            type="textarea"
            v-model="addForm.desc"
            placeholder="请输入备注(不超过40个字)"
            maxlength="15"
            show-word-limit
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClose" class="el-button--first">取 消</el-button>
        <el-button type="warning" class="el-button--second" @click="addSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 新建 工单弹窗 -->

    <!-- 工单配置弹框 -->
    <el-dialog
      title="工单配置"
      :visible.sync="configVisible"
      width="630px"
      :before-close="configClose"
      class="congigDialog"
    >
      <el-form
        label-width="140px"
        class="configForm"
      >
        <el-form-item
          label="补货警戒线:"
          prop="alertValue"
        >
          <el-input-number
            style="width: 80%"
            v-model="num"
            controls-position="right"
            :min="1"
            :max="100"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="configClose" type="primary" class="el-button--first"
          >取 消</el-button
        >
        <el-button type="danger" class="el-button--second" @click="configSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 工单配置弹框 -->
    <!-- 操作的详情弹框 -->
    <el-dialog
      title="工单详情"
      :visible.sync="detailVisible"
      width="630px"
      :before-close="detailClose"
      class="detailDialog"
    >
      <template>
        <div class="task-status" v-if="detailType === 4">
          <img class="icon" src="@/assets/lkd/done1.png" alt="" />
          <span class="status">完成</span>
          <img class="pic" src="@/assets/lkd/done2.png" alt="" />
        </div>
        <div class="task-status" v-else-if="detailType === 3">
          <img class="icon" src="@/assets/lkd/cancel1.png" alt="" />
          <span class="status">取消</span>
          <img class="pic" src="@/assets/lkd/cancel2.png" alt="" />
        </div>
        <div class="task-status" v-else>
          <img class="icon" src="@/assets/lkd/undetermined1.png" alt="" />
          <span class="status">待办</span>
          <img class="pic" src="@/assets/lkd/undetermined2.png" alt="" />
        </div>
        <el-form label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备编号:">
                {{ detailRow.innerCode }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建日期:">
                {{ detailRow.createTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="detailType === 4">
              <el-form-item label="完成日期:">
                {{ detailRow.updateTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="detailType === 3">
              <el-form-item label="取消日期:">
                {{ detailRow.updateTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运营人员:">
                {{ detailRow.userName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单类型:">
                {{ detailRow.taskType?.typeName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="补货数量:">
                <!-- 补货详情弹窗 -->
                <el-dialog
                  title="补货详情"
                  :visible.sync="buhuoVisible"
                  width="630px"
                  :before-close="buhuoClose"
                  class="buhuoDialog"
                  append-to-body
                >
                  <!-- 补货清单表格区域 -->
                  <BuHuo :channelList="channelList" :isShow="isShow"></BuHuo>
                  <!-- 补货清单表格区域 -->
                </el-dialog>
                <!-- 补货详情弹窗 -->
                <el-button
                  icon="el-icon-edit"
                  type="text"
                  @click="buhuoFn"
                  >补货详情</el-button
                >
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单方式:">
                {{ detailRow.createType ? "手动" : "自动" }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注:">
                {{ detailRow.desc }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <span slot="footer" class="dialog-footer" v-if="detailType !== 4">
        <el-button
          @click="cancelOrDoneDialog"
          type="primary"
          class="el-button--first"
          >{{ detailType === 3 ? "重新创建" : "取消工单" }}</el-button
        >
      </span>
    </el-dialog>
    <!-- 操作的详情弹框 -->
  </div>
</template>

<script>
import dayjs from 'dayjs'
import {
  getallTaskStatus,
  getTaskSearch,
  getTaskType,
  getAlertValue,
  autoSupplyConfig,
  getOperatorList,
  taskCreate,
  getTaskInfo,
  TaskCancel,
  getChannelList,
  getTaskDetails
} from '@/api/operation'
import BuHuo from './component/BuHuo.vue'
export default {
  components: {
    BuHuo
  },
  created () {
    this.getallTaskStatus()
    this.getTaskSearch()
    this.getTaskType()
  },
  data () {
    return {
      isShow: '',
      formData: {
        taskCode: '',
        status: ''
      },
      allTaskStatus: [],
      taskType: [],
      page: {
        pageIndex: 1,
        pageSize: 10,
        isRepair: false,
        totalCount: 0,
        totalPage: 0
      },
      tableData: [],
      loading: false,
      // 工单配置
      configVisible: false,
      num: 1,
      // 工单配置
      // 新建 工单
      addVisible: false,
      addForm: {
        username: '',
        assignorId: '',
        createType: 1,
        innerCode: '',
        userId: 1,
        productType: '',
        desc: '',
        details: []
      },
      operatorList: [],
      addRules: {
        innerCode: [{ required: true, message: '不能为空', trigger: 'blur' }],
        productType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        userName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      // 新建 工单
      // 操作里面的详情  待做完
      buhuoVisible: false,
      channelList: [],
      detailType: '',
      detailVisible: false,
      detailRow: {}
      // 操作里面的详情
    }
  },
  methods: {
    async getTaskType () {
      this.taskType = await getTaskType()
    },
    async getallTaskStatus () {
      this.allTaskStatus = await getallTaskStatus()
    },
    async getTaskSearch () {
      try {
        this.loading = true
        const res = await getTaskSearch({ ...this.page, ...this.formData })
        console.log(res)
        this.tableData = res.currentPageRecords
        this.page.totalCount = Number(res.totalCount)
        this.page.totalPage = Number(res.totalPage)
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    handleCurrentChange () {
      this.getTaskSearch()
    },
    onSearch () {
      this.getTaskSearch()
    },
    // 新增 工单的弹框
    addFn () {
      this.addVisible = true
    },
    addClose () {
      this.addForm = {
        innerCode: '',
        productType: '',
        userId: '',
        desc: ''
      }
      this.$refs.addForm.resetFields()
      this.addVisible = false
    },
    async getOperatorList () {
      const res = await getOperatorList(this.addForm.innerCode)
      this.operatorList = res
      console.log(res)
    },
    async addSubmit () {
      try {
        await taskCreate(this.addForm)
        this.addClose()
        this.getTaskSearch()
      } catch (error) {
        console.log(error)
        this.$message.error(error.response.data)
      }
    },
    async cancelOrDoneDialog () {
      // 如果是取消工单，获取工单详情，弹出新建工单
      if (this.detailType === 3) {
        this.addVisible = true
        const res = await getTaskInfo(this.detailRow.taskId)
        this.addForm.innerCode = res.innerCode
        this.getOperatorList(this.addForm.innerCode)
        // 下拉框v-model绑定的值与value的值一样就代表默认选中
        this.addForm.assignorId = res.assignorId
        this.addForm.productType = res.taskType.typeId
      } else {
        // 如果是代办状态，弹出取消确认框
        this.$confirm('取消工单后，将不能恢复，是否确认取消?', '取消工单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await TaskCancel(this.detailRow.taskId)
            this.getTaskSearch()
            this.detailClose()
          } catch (error) {
            console.log(error)
          }
        })
      }
    },
    async buhuoFn () {
      this.buhuoVisible = true
      this.isShow = false
      this.channelList = await getTaskDetails(this.detailRow.taskId)
    },
    // 新增 工单的弹框
    // 操作的详情
    clickDetailFn (row) {
      this.detailVisible = true
      this.detailRow = row
      this.detailRow.createTime = dayjs(row.createTime).format(
        'YYYY.MM.DD HH:mm:ss'
      )
      this.detailRow.updateTime = dayjs(row.updateTime).format(
        'YYYY.MM.DD HH:mm:ss'
      )
      // 4个状态 1待办是2是进行3是取消4是完成
      this.detailType = this.detailRow.taskStatus
    },
    detailClose () {
      this.detailVisible = false
    },
    // 操作的详情

    // 工单配置的弹框
    configClose () {
      this.configVisible = false
    },
    async configFn () {
      this.configVisible = true
      this.num = await getAlertValue()
    },
    async configSubmit () {
      await autoSupplyConfig({ alertValue: this.num })
      this.configVisible = false
    },
    // handleChange (num) {
    //   this.configForm.alertValue = this.configForm.alertValue + num
    // },
    // 工单配置的弹框

    // 创建的类型是手动还是自动
    formatterCreateType (row, column, cellValue, index) {
      if (cellValue === 0) return '自动'
      if (cellValue === 1) return '手动'
    },
    // 把创建世间传上去
    formatterCreateTime (row, column, cellValue, index) {
      return dayjs(cellValue).format('YYYY.MM.DD HH:mm:ss')
    },
    // 补货清单 弹窗
    buhuoClose () {
      this.buhuoVisible = false
    },
    buhuoDetailFn () {
      this.$refs.addForm.validateField('innerCode', async (msg) => {
        if (!msg) {
          // 有设备编号，显示弹框，获取补货详情
          this.buhuoVisible = true
          this.isShow = true
          const res = await getChannelList(this.addForm.innerCode)
          res.forEach(item => {
            item.expectCapacity = (item.maxCapacity - item.currentCapacity) > 0 ? (item.maxCapacity - item.currentCapacity) : 0
          })
          res.forEach(item => {
            item.max = item.expectCapacity
          })
          this.channelList = res
        }
      })
    },
    buhuoSubmit () {
      // 拿到补货详情页面的数据details
      this.addForm.details = this.channelList.filter(item => item.sku).map(item => ({
        channelCode: item.channelCode,
        expectCapacity: item.expectCapacity,
        skuId: item.skuId,
        skuImage: item.sku.skuImage,
        skuName: item.sku.skuName
      }))
      this.buhuoVisible = false
    }
    // 补货清单 弹窗
  },
  computed: {
    buhuoTaskType () {
      // 根据类型的id去筛选其中一种类型   这里选择id为2的buhuogongdan
      return this.taskType.filter((item) => item.typeId === 2)
    }
  }
}
</script>

<style lang="scss" scoped >
.header {
  width: 100%;
  background-color: #fff;
  line-height: 30px;
}
.header .el-form {
  width: 100%;
  margin-left: 15px;
}
.operationorder-page {
  .el-card {
    border-radius: unset;
    border: unset;
  }
  .search.el-card {
    margin-bottom: 20px;
    height: 64px;
    display: flex;
    align-items: center;
    padding-left: 17px;
    background-color: #fff;
    .el-card__body {
      padding: unset;
      .el-form-item {
        margin: unset;
        margin-right: 10px;
      }
    }
  }
  .el-button {
    border: none !important;
    // padding: 0 30px;  待做
    // margin-bottom: 30px;
    &.el-button--first {
      background-color: #fbf4f0 !important;
      color: #f3e7e1 !important;

      &:hover {
        background-color: #f3e7e1 !important;
      }
    }
  }
}
.el-table-column {
  background-color: #f3f6fb;
}

::v-deep .el-input-number {
    width: 100%
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
// 去除table的网格线  文档属性border只能去掉竖线，不能去掉横线
::v-deep .el-table td.el-table__cell {
  border: 0px;
}
::v-deep .el-table th.el-table__cell.is-leaf {
  background-color: #f3f6fb;
}
// ::v-deep .el-table thead {
// background-color: #f3f6fb;
// }
::v-deep .el-dialog .el-dialog__body .el-form-item {
  margin-bottom: 20px;
}
.el-table {
  ::v-deep th {
    padding: 10px, 0;
    background-color: rgb(243, 246, 251);
    border: none;
  }
  ::v-deep tr {
    color: #666;
    font-size: 14px;
    padding: 2px 0;
    border: none;
  }
  ::v-deep td {
    padding: 2px 0;
    border: none;
  }
}
::v-deep .el-card__body {
  padding: 0;
  margin-top: 20px;
}
.el-pagination {
    display: flex;
    height: 96px;
    align-items: center;
    .el-pagination__total {
      flex: 1;
      font-size: 16px !important;
      color: #dbdfe5 !important;
    }
    ::v-deep button:disabled {
      color: #d8dde3;
      background: #edf0f9;
    }
    ::v-deep button {
      width: 70px;
      height: 32px;
      margin: 0 16px;
      border-radius: 2px;
      background-color: #d5ddf8;
    }
  }
</style>
